<!--
 * @Author       : wfl
 * @LastEditors: fj
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-07-26 18:38:58
 * @LastEditTime: 2023-08-10 12:28:34
-->
<script lang="ts" setup name="SmsTemplateChannel">
import { _ } from 'iking-utils'
import type { FormInstance } from 'element-plus'
import { useChannel } from './useChannel'
import { msgApi } from '@/MainApp/apis/msg'
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits<{
  (e: 'close'): void
}>()
const { lenContent } = useLength()
const injectTepForm: Ref<any> | undefined = inject('tempForm')
const smsFormRef: Ref<FormInstance | null> = ref(null)
const smsForm = computed(() => {
  if (!props.data?.id) {
    props.data.voice = false
    props.data.templateId = props.data.templateId || injectTepForm?.value?.id
    props.data.supportTemplate = true
  }
  return props.data
})
const dedupe = (array: any[], key: any) => {
  if (!array)
    return []
  const seen = new Set()
  return array.filter(item => {
    const k = item[key]
    return seen.has(k) ? false : seen.add(k)
  })
}
const paramList: any = computed(() => {
  if (paramList.value)
    return paramList.value
  else
    return dedupe(_.cloneDeep(props.data.paramDefinitions), 'paramName')
})
const { loading, handSaveUnnable, handEnable, handCancel, msgError, linkHolder, linkRule } = useChannel(props.isEdit, smsForm)

// TODO
const smsList: Ref<any> = ref([])
const smsTempList: Ref<any> = ref([])
const smsParams: Ref<any> = ref([])
const paramDefinitionList: Ref<any> = ref([])
const getsmsList = async () => {
  const { msg, data, success } = await msgApi.getSmsTemplateList({ supportTemplate: true })
  if (!success)
    msgError(msg)
  smsList.value = data || []
  if (props.data.channelId)
    getsmsTempList(props.data.channelId, true)
}
getsmsList()

const tempLoading = ref(false)
/**
 * @description: 根据短信（wechatMiniId）获取模板列表
 * @param {*} id
 * @return {*}
 */
const getsmsTempList = async (id: string, isEdit = false) => {
  if (!isEdit) {
    smsForm.value.channelTemplateId = ''
    smsForm.value.content = ''
    smsParams.value = []
  }
  tempLoading.value = true
  const { msg, data, success } = await msgApi.getSmsTemplateApi(id)
  tempLoading.value = false
  if (!success)
    msgError(msg)
  smsTempList.value = data || []
  if (props.data?.channelTemplateId)
    handChangeSmsTemp(props.data.channelTemplateId)
}
/**
 * @description: 根据选择模板，获取模板参数
 * @return {*}
 */
const handChangeSmsTemp = (id: string) => {
  const temp = smsTempList.value.find((item: any) => item.id === id)
  if (temp) {
    smsForm.value.content = temp.content
    smsParams.value = temp.params

    paramDefinitionList.value = temp.params.map((mappedParamName: string) => {
      return {
        mappedParamName,
        paramName: null
      }
    })
  }
}

const handChange = (id: string, _row: any, index: number) => {
  const row = paramList.value.find((item: any) => item.paramName === id) || {}
  smsForm.value.paramDefinitions[index] = {
    ...row,
    ..._row
  }
}

const cancel = () => {
  smsFormRef.value?.resetFields()
  paramDefinitionList.value = []
  emits('close')
}
</script>

<template>
  <el-form
    ref="smsFormRef"
    v-loading="loading"
    label-width="100px"
    :model="smsForm"
    label-position="top"
  >
    <el-row :gutter="12">
      <el-col :span="12">
        <IkFormItemTitle label="短信平台" prop="channelId" title="（点击参数名称，将参数插入消息内容）">
          <el-select v-model="smsForm.channelId" placeholder="请选择短信平台" @change="getsmsTempList">
            <el-option
              v-for="item in smsList"
              :key="item.smsId"
              :label="item.name"
              :value="item.smsId"
            />
          </el-select>
        </IkFormItemTitle>
      </el-col>
      <el-col :span="12">
        <el-form-item v-loading="tempLoading" label="消息模板" prop="channelTemplateId">
          <el-select v-model="smsForm.channelTemplateId" placeholder="请选择消息模板" @change="handChangeSmsTemp">
            <el-option
              v-for="item in smsTempList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="模板内容预览" prop="content">
      <el-input
        v-model.trim="smsForm.content"
        :autosize="{ minRows: 3, maxRows: 8 }"
        type="textarea"
        disabled
      />
    </el-form-item>
    <el-form-item label="参数配置" label-width="120px">
      <el-table
        class="small"
        :data="paramDefinitionList"
        border
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="55"
        />
        <el-table-column prop="mappedParamName" label="短信模板参数" />
        <el-table-column prop="paramName" label="消息参数">
          <template #default="paramConfig">
            <el-form-item label="" label-width="0" prop="row.paramName">
              <el-select v-model="paramConfig.row.paramName" clearable @change="handChange($event, paramConfig.row, paramConfig.$index)">
                <el-option
                  v-for="item in paramList"
                  :key="item.paramName"
                  :label="`${item.paramDescription}(${item.paramName})`"
                  :value="item.paramName"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <IkFormItemTitle
      v-if="isEdit && smsForm.id && smsForm.redirectDefinitions?.[0]"
      label="跳转链接"
      prop="redirectDefinitions[0].redirectTo"
      title="（点击消息后的跳转链接）"
      :rules="linkRule"
      :placeholder="linkHolder"
    >
      <el-input v-model.trim="smsForm.redirectDefinitions[0].redirectTo" :max-length="lenContent" />
    </IkFormItemTitle>
    <IkFormItemTitle
      v-else
      label="跳转链接"
      prop="redirectDefinitions"
      title="（点击消息后的跳转链接）"
      :rules="linkRule"
      :placeholder="linkHolder"
    >
      <el-input v-model.trim="smsForm.redirectDefinitions" :max-length="lenContent" />
    </IkFormItemTitle>
    <el-form-item v-if="!isEdit" label="" class="ik-msg-channel">
      <el-button type="primary" text @click="handEnable()">启用</el-button>
      <el-button type="primary" text @click="handSaveUnnable()">保存不启用</el-button>
      <el-button @click="cancel()">取消</el-button>
    </el-form-item>
  </el-form>
  <IkPageFooter v-if="isEdit">
    <el-button @click="handCancel()">取消</el-button>
    <el-button type="primary" @click="handSaveUnnable()">保存不启用</el-button>
    <el-button type="primary" @click="handEnable()">启用</el-button>
  </IkPageFooter>
</template>

<style lang="scss" scoped>
.ik-msg-channel {
  :deep(.el-form-item__content) {
    justify-content: end;
  }
}
</style>
